package com.wufun.overseas.main.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.utils.DensityUtil;
import com.wufun.baselibrary.widgets.NoSwipeViewPager;
import com.wufun.overseas.R;
import com.wufun.overseas.adapters.MyFragmentAdapter;
import com.wufun.overseas.common.TabTypeInterface;
import com.wufun.overseas.dot.DotService;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.main.fragment.DetailFragment;
import com.wufun.overseas.main.fragment.HomeFragment;
import com.wufun.overseas.main.fragment.SettingFragment;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.models.event.DownloadResultEvent;
import com.wufun.overseas.tools.DownloadManager;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends MyActivity {

    @Bind(R.id.main_viewpager)
    NoSwipeViewPager mainViewpager;
    @Bind(R.id.view_line)
    View viewLine;
    @Bind(R.id.tab_home)
    RadioButton tabHome;
    @Bind(R.id.tab_play)
    RadioButton tabPlay;
    @Bind(R.id.tab_setting)
    RadioButton tabSetting;
    @Bind(R.id.tabs_rg)
    RadioGroup tabsRg;
    @Bind(R.id.main_tip_iv)
    ImageView mainTipIv;

    private Fragment currentFragment; //当前fragment
    private MyFragmentAdapter adapter;
    private final String HOME_TAG = "home";
    private final String SETTING_TAG = "setting";
    private final String Detail_TAG = "detail";

    private int beforId = 0;
    private int index;
    private int margin = 0;

    /**
     * ServiceConnection代表与服务的连接，它只有两个方法，
     * onServiceConnected和onServiceDisconnected，
     * 前者是在操作者在连接一个服务成功时被调用，而后者是在服务崩溃或被杀死导致的连接中断时被调用
     */
    private ServiceConnection conn;
    private DotService mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        index = intent.getIntExtra("index", 0);
        switch (index) {
            case 0:
                //HomeFragment
                selectItemView(0);
                break;
            case 1:
                selectItemView(1);
                break;
            case 2:
                selectItemView(2);
                break;
        }

        margin = DensityUtil.dp2px(mContext, 15);

        int leftM = getmWidth()*5/6;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                , ViewGroup.LayoutParams.WRAP_CONTENT);
        params.leftMargin = leftM + margin;
        params.topMargin = margin/2;
        mainTipIv.setLayoutParams(params);

        initDotService();
    }

    private void initDotService() {
//        conn = new ServiceConnection() {
//
//            /**
//             * 与服务器端交互的接口方法 绑定服务的时候被回调，在这个方法获取绑定Service传递过来的IBinder对象，
//             * 通过这个IBinder对象，实现宿主和Service的交互。
//             */
//            @Override
//            public void onServiceConnected(ComponentName name, IBinder service) {
//                // 获取Binder
//                DotService.LocalBinder binder = (DotService.LocalBinder) service;
//                mService = binder.getService();
//            }
//
//            /**
//             * 当取消绑定的时候被回调。但正常情况下是不被调用的，它的调用时机是当Service服务被意外销毁时，
//             * 例如内存的资源不足时这个方法才被自动调用。
//             */
//            @Override
//            public void onServiceDisconnected(ComponentName name) {
//                mService=null;
//            }
//        };
//
//        //调用绑定方法
//        bindService(new Intent(mContext, DotService.class), conn, Service.BIND_AUTO_CREATE);

        startService(new Intent(mContext, DotService.class));
    }

    @Override
    protected void onDestroy() {
//        // 解除绑定
//        if(mService!=null) {
//            mService = null;
//            unbindService(conn);
//        }
        super.onDestroy();
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);

        hideTitleBar();

        initViewpager();
        initBottomBar();

//        addDownloadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkShow();
    }

    @Override
    public void onUserEvent(DownloadResultEvent eventData) {
        super.onUserEvent(eventData);
        if (eventData.status != CommonDownloadTask.STATUS_PROGRESS) {
            checkShow();
            if (currentFragment instanceof SettingFragment){
                ((SettingFragment) currentFragment).fragmentEvent(eventData);
            }
        }
    }

    private void checkShow() {
        if (DownloadManager.getInstance().getAllNotFinishDownload()) {
            mainTipIv.setVisibility(View.VISIBLE);
        } else {
            mainTipIv.setVisibility(View.INVISIBLE);
        }
    }

    private void addDownloadData() {

        String url = "http://ctappdownload.5fun.com/appsite/simulator/mame/dino_1_2.1.20_80.zip";
        String zipName = "dino.zip";
        long zipSize = 4772130;
        String filedir = MyApplication.getMyApplication().getAppRootPath();

        DownLoadModel temp = new DownLoadModel(
                url,
                "",
                filedir,
                filedir + zipName.replace(".zip", ""),
                filedir + zipName,
                zipSize,
                "29.76M",
                TabTypeInterface.TYPE_ACTION,
                CommonDownloadTask.STATUS_NORMAL,
                0,
                zipName.replace(".zip", ""),
                zipName,
                "",
                "0",
                System.currentTimeMillis(),
                ""
        );

        DownloadManager mDownloadManager = DownloadManager.getInstance();
//        mDownloadManager.getAllDownload();
//        File file = new File(filedir);
//        FileUtils.deleteFile(file);
//        mDownloadManager.deleteAllDownload();

        if (!mDownloadManager.isExist(temp.getDownloadUrl()))
            mDownloadManager.insertDownload(temp);
    }

    private void initBottomBar() {

        tabsRg = (RadioGroup) findViewById(R.id.tabs_rg);
        tabsRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.tab_home:
                        selectItemView(0);
                        beforId = 0;
                        break;
                    case R.id.tab_play:
                        if (beforId == 0) {
                            beforId = 0;
                            tabHome.setChecked(true);
                        } else if (beforId == 2) {
                            beforId = 2;
                            tabSetting.setChecked(true);
                        }
                        startActivity(new Intent(mContext, PlayMainActivtiy.class));
                        break;
                    case R.id.tab_setting:
                        selectItemView(1);
                        beforId = 2;
                        break;
                }
            }
        });

        //挨着给每个RadioButton加入drawable限制边距以控制显示大小
//        RadioButton[] bt = {tabOfferReward, tabMall, tabPersonal};
//        for (int i = 0; i < bt.length; i++) {
//            Drawable[] drs = bt[i].getCompoundDrawables();
//            Rect r = new Rect(0, 0, drs[1].getMinimumWidth(), drs[1].getMinimumHeight());
//            drs[1].setBounds(r);
//            bt[i].setCompoundDrawables(null, drs[1], null, null);
//        }
    }

    private void initViewpager() {
        mainViewpager.setPagingEnabled(false);//是否支持手势滑动
        adapter = new MyFragmentAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), HOME_TAG);
        adapter.addFragment(new SettingFragment(), SETTING_TAG);
        adapter.addFragment(new DetailFragment(), Detail_TAG);
        mainViewpager.setOffscreenPageLimit(3);
        mainViewpager.setAdapter(adapter);
        mainViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    tabsRg.getChildAt(position).performClick();
                }
                currentFragment = adapter.getItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        selectItemView(0);
    }

    public void selectItemView(int i) {
        mainViewpager.setCurrentItem(i, true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && (mAty instanceof MainActivity)) {// 返回键
            if (currentFragment instanceof SettingFragment || currentFragment instanceof DetailFragment) {
                selectItemView(0);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
